﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Empires.PL.PageHandler;
using Empires.PL.PageBuilder;
using Empires.PL.Web.Models;
using Empires.PL.ServiceClient;

namespace Empires.PL.Web.Controllers
{
    [HandlerError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            return View();
        }
        public ActionResult Service()
        {
            return View();
        }

        public ActionResult ServiceDetail()
        {
            return View();
        }

        public ActionResult Blog(int Id = 0)
        {
            ViewData["Status"] = Empires.PL.ServiceClient.AppUserServiceClient.GetUserStatus(
                HttpContext.User.Identity.Name);
           var list = Empires.PL.ServiceClient.AppBlogServiceClient.GetBlogs(Id, 4);
           var popular = Empires.PL.ServiceClient.AppBlogServiceClient.GetPopularBlogs(4);
           var newarticles = Empires.PL.ServiceClient.AppBlogServiceClient.GetBlogs(0, 5);
           ViewData["Articles"] = list;
           ViewData["Popular"] = popular;
           ViewData["NewArticles"] = newarticles;
           ViewData["pagination"] = PL.PageBuilder.ControlBuilder.BuildPagination(Id, 4, list.First().ITEMCOUNT, "/Home/Blog/{0}");
            return View();
        }
        public ActionResult NewBlog()
        {
            int status = Empires.PL.ServiceClient.AppUserServiceClient.GetUserStatus(
                HttpContext.User.Identity.Name);
            if (status < 2)
            {
                return RedirectToAction("Blog");
            }
            ViewData["username"] = HttpContext.User.Identity.Name;
            return View();
        }
        public string UpLoadFile(string type)
        {
            var file = HttpContext.Request.Files["filedata"];
            var filetype = file.ContentType; //image/x-png;image/gif;image/pjpeg
            if (!filetype.Contains("image"))
            {
                return String.Format("{'error':'{0}','msg':'{1}'}","上传文件格式错误，必须为图片文件","");               
            }
            var filelength = file.ContentLength;
            if (filelength > 2097152) //2M
            {
                return String.Format("{'error':'{0}','msg':'{1}'}", "上传文件必须小于2M", "");                 
            }
            var filename = file.FileName;
            string extname = filename.Substring(filename.LastIndexOf('.'));
            string newfilename = DateTime.Now.ToString("ddMMyyyy-hhmmss") + extname;
            string dir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Content\\\\CustomerFiles\\\\Blog\\\\" + newfilename;
            file.SaveAs(dir);
            dir = type == "1" ? "!" + dir : dir;
            return "{error:\"\",msg:\"" + dir.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "\\\\") + "\"}";
            //file.SaveAs(AppDomain.CurrentDomain.SetupInformation.ApplicationBase+"\\Content\\CustomerFiles\\Blog"+
        }     
        [HttpPost]
        public ActionResult PostBlogArticle(string author, string title, string article)
        {
            var file = HttpContext.Request.Files["bgimage"];
            var stfile = HttpContext.Request.Files["bgstimage"];
            var filetype = file.ContentType; //image/x-png;image/gif;image/pjpeg
            var stfiletype = stfile.ContentType;
            if (!filetype.Contains("image") || !stfiletype.Contains("image"))
            {
                return Redirect("/Home/PostArticleFault?result=imgtype");
            }
            var filelength = file.ContentLength;
            var stfilelength = stfile.ContentLength;
            if (filelength > 2097152 || stfilelength > 2097152) //2M
            {
                return Redirect("/Home/PostArticleFault?result=imglength");
            }
            var filename = file.FileName;
            var stfilename = stfile.FileName;
            string extname = filename.Substring(filename.LastIndexOf('.')); //扩展名
            string stextname = stfilename.Substring(stfilename.LastIndexOf('.'));

            string newfilename = title + DateTime.Now.ToString("ddMMyyyy-hhmmss") + extname;
            string stnewfilename = title + "st_" + DateTime.Now.ToString("ddMMyyyy-hhmmss") + extname;
            string dir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Content\\CustomerFiles\\Blog\\" + newfilename;
            string stdir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Content\\CustomerFiles\\Blog\\" + stnewfilename;
            file.SaveAs(dir);
            stfile.SaveAs(stdir);

            int id = Empires.PL.ServiceClient.AppBlogServiceClient.PostArticle(
                DateTime.Now, author, title, dir.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "\\"),
                stdir.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "\\").Replace("\\","/"), article);
            return Redirect("/Home/PostArticleSuccess/" + id);
        }
        public ActionResult PostArticleFault(string result)
        {
            return View();
        }
        public ActionResult PostArticleSuccess(int Id)
        {
            return View();
        }
        public ActionResult Article(int Id, int page = 0)
        {
            var item = PL.ServiceClient.AppBlogServiceClient.GetArticle(Id);
            var list = PL.ServiceClient.AppBlogServiceClient.GetArticleReply(Id, page, 5);
            var popular = Empires.PL.ServiceClient.AppBlogServiceClient.GetPopularBlogs(4);
            var newarticles = Empires.PL.ServiceClient.AppBlogServiceClient.GetBlogs(0, 5);
            ViewData["article"] = item;
            ViewData["replay"] = list;
            ViewData["Popular"] = popular;
            ViewData["NewArticles"] = newarticles;
            ViewData["Id"] = Id;
            string pagination = PL.PageBuilder.ControlBuilder.BuildPagination(page, 5, item.REPLYTIME, "/Home/Article/{0}");
            ViewData["pagination"] = pagination;

            ViewData["nickname"] = HttpContext.User.Identity.IsAuthenticated ?
                PL.ServiceClient.AppUserServiceClient.GetUserNickname(HttpContext.User.Identity.Name) : "游客";
            return View();
        }
        [HttpPost]
        public ActionResult PostArticleComment(int Id, string author, string content)
        {
            int i = PL.ServiceClient.AppBlogServiceClient.PostArticleReply(Id, author, content);
            ViewData["result"] = i;
            return View();
        }
        public ActionResult Contact()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Contact(ContactModel model)
        {
            AppContactServiceClient.PostContactMessage(model.Appellaction, model.Contact, model.Title, model.Message);
            return View();
        }
        public ActionResult Templetes()
        {
            return View();
        }
        public ActionResult TempleteDetail(int Id)
        {
            var info = AppTempleteServiceClient.GetTempleteInfo(Id);
            ViewData["Id"] = info.Id;
            ViewData["templeteName"] = info.TempleteName;
            ViewData["descript"] = info.Descript;
            ViewData["mainimage"] = info.MainImage;
            ViewData["templeteimages"] = info.TempleteImages;
            return View();
        }
        [Authorize]
        public ActionResult ApplyTemplete(int Id)
        {
            if (ServiceClient.AppTempleteServiceClient.ApplyTempleteToCompany(
                HttpContext.User.Identity.Name, Id) != 1)
            {
                //如果返回值不唯1，跳转异常页面
            }
            return View();
        }
        #region 应用模板验证
        /// <summary>
        /// 检查是否登录（用户是否被锁定）
        /// </summary>
        /// <returns></returns>
        public int CheckisAuthentication()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                return 1;
            }
            return 0;
        }
        /// <summary>
        /// 检查是否开通网站
        /// </summary>
        /// <returns>如果开启了网站，返回站点名字</returns>
        public string CheckIsMaster()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                return Empires.PL.ServiceClient.AppUserServiceClient.GetUserWebSiteName(
                    HttpContext.User.Identity.Name);
            }
            return string.Empty;
        }
        #endregion
        public ActionResult Error()
        {
            return View();
        }
    }
}
